<template>
  <div>
    <el-card>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>轮播图管理</el-breadcrumb-item>
        <el-breadcrumb-item>轮播图列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-form
        :inline="true"
        :model="swiperQuery"
        class="demo-form-inline"
        style="margin-top: 20px"
        size="large"
      >
        <el-form-item label="跳转链接">
          <el-input
            v-model="swiperQuery.link"
            placeholder="请输入跳转链接"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="图片alt">
          <el-input
            v-model="swiperQuery.alt"
            placeholder="请输入图片alt"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="clear">清空</el-button>&nbsp;
          <el-button type="primary" @click="getSwiperListData">搜索</el-button
          >&nbsp;
          <el-button type="success" @click="dialogVisible = true"
            >+新增轮播图</el-button
          >
        </el-form-item>
        <!-- <Teleport to="#app">
          <div
            style="
              width: 200px;
              height: 30px;
              background-color: red;
              position: relative;
            "
          ></div>
        </Teleport> -->
      </el-form>
    </el-card>
    <el-card style="margin-top: 15px">
      <el-table :data="swiperList">
        <el-table-column label="轮播图图片">
          <template #default="{ row }">
            <el-image
              style="width: 100px; height: 80px"
              :src="row.img"
              :preview-src-list="[row.img]"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column label="轮播图图片">
          <template #default="{ row }">
            <a :href="row.link" target="__blank">{{ row.link }}</a>
          </template>
        </el-table-column>
        <el-table-column label="轮播图alt" prop="alt"></el-table-column>
        <el-table-column label="启用/禁用">
          <template #default="{ row }">
            <!-- v-model双向数据绑定才能交互、单向数据绑定只能渲染，不能交互 -->
            <el-switch
              :model-value="row.flag"
              :active-value="true"
              :inactive-value="false"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" @click="edit(row)">修改</el-button>
            <el-button type="danger" @click="del(row.bannerid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="swiperQuery.page"
        v-model:page-size="swiperQuery.pageSize"
        :page-sizes="[1, 2, 10]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="getSwiperListData"
        @current-change="getSwiperListData"
      />
      <!-- 新增、修改轮播图dialog -->
      <el-dialog
        v-model="dialogVisible"
        :title="mode === 'add' ? '新增' : '修改'"
        width="50%"
      >
        <el-form
          ref="ruleFormRef"
          :rules="rules"
          :model="ruleForm"
          size="large"
          label-width="120px"
        >
          <el-form-item label="轮播图图片" prop="img">
            <!-- 
              跟axios没有关系，所以action要写全!!!
              v-model:file-list 视图中渲染的图片数组（数据驱动视图）
              action：上传的服务器地址 
              limit：允许上传的图片最大张数
              list-type="picture-card" 以卡片的形式展示图片
              on-preview：预览（给预览地址设置值，然后弹出预览的对话框）
              on-remove：移除图片，fileList中的元素会被移除
              on-success：上传成功的回调（拿到服务上传之后的响应）
            -->
            <el-upload
              v-model:file-list="fileList"
              :action="action"
              :limit="1"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
            >
              <el-icon><i-ep-plus /></el-icon>
            </el-upload>
            <el-dialog v-model="previewDialogVisible" title="图片预览">
              <img w-full :src="prviewImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
          <el-form-item label="跳转链接" prop="link">
            <el-input v-model="ruleForm.link" />
          </el-form-item>
          <el-form-item label="alt说明">
            <el-input v-model="ruleForm.alt" />
          </el-form-item>
          <el-form-item label="启用/禁用">
            <el-switch
              v-model="ruleForm.flag"
              :active-value="true"
              :inactive-value="false"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submit"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="SwiperList">
import { ref, reactive, watch, onUnmounted } from 'vue'
import type { SwiperQuery, Swiper } from '@/types/swiper'
import {
  getSwierList,
  addSwiper,
  updateSwiper,
  deleteSwiper
} from '@/api/swiper'
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules
} from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'

const swiperQuery = ref({
  link: '',
  alt: '',
  page: 1,
  pageSize: 2
} as SwiperQuery)

const total = ref(0)
const swiperList = ref([] as Swiper[])

const clear = () => {
  swiperQuery.value.link = ''
  swiperQuery.value.alt = ''

  getSwiperListData()
}

const getSwiperListData = async () => {
  const res = await getSwierList(swiperQuery.value)

  total.value = res.data.data.total
  swiperList.value = res.data.data.items
}

getSwiperListData()

const isEditing = ref(false)
onUnmounted(() => {
  // if (isEditing.value) {
  localStorage.setItem(
    'unsubmit',
    JSON.stringify({
      name: 'zhangsan',
      age: 20
    })
  )
  // }
})

/***************轮播图新增和修改********************/
const dialogVisible = ref(false)
const mode = ref<'add' | 'edit'>('add')
const ruleFormRef = ref<FormInstance>()

const rules = reactive<FormRules<Swiper>>({
  img: [{ required: true, message: '轮播图图片不能为空', trigger: 'blur' }],
  link: [{ required: true, message: '跳转链接不能为空', trigger: 'blur' }]
})

const ruleForm = ref<Swiper>({
  bannerid: '',
  img: '', // 上传成功之后得到的图片地址
  link: '',
  alt: '',
  flag: true
})

const edit = (row: Swiper) => {
  isEditing.value = true

  mode.value = 'edit'

  ruleForm.value = { ...row } // 一层深拷贝

  // 单独要给上传的fileList赋值
  fileList.value = [{ url: row.img, uid: Math.random() }] as UploadUserFile[]

  dialogVisible.value = true
}

const submit = async () => {
  if (ruleFormRef.value) {
    try {
      await ruleFormRef.value.validate()

      mode.value === 'add'
        ? addSwiper(ruleForm.value)
        : updateSwiper(ruleForm.value)

      // 提示
      ElMessage.success(mode.value === 'add' ? '新增成功~' : '修改成功~')

      // 重新查询轮播图列表
      getSwiperListData()

      // 关闭弹框
      dialogVisible.value = false
      isEditing.value = false
    } catch (error) {
      console.log('---error---', error)
    }
  }
}

watch(dialogVisible, newValue => {
  if (!newValue) {
    mode.value = 'add'

    // newValue为fasle的情况代表关闭
    ruleFormRef.value?.resetFields() // 清空校验

    // 清空模型值，表单中的内容也清空了
    ruleForm.value = {
      bannerid: '',
      img: '',
      flag: true,
      link: '',
      alt: ''
    }

    // 清空上传文件中的图片
    fileList.value = []
  }
})

// 删除轮播图
const del = (bannerid: string) => {
  ElMessageBox.confirm('确定删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await deleteSwiper(bannerid)

      // 重新查询
      getSwiperListData()

      // 提示
      ElMessage.success('删除成功~')
    })
    .catch(() => {})
}

/***************************图片上传******************************/
const previewDialogVisible = ref(false)
const prviewImageUrl = ref('')
const action = ref(import.meta.env.VITE_BASEURL + 'file/upload') // 上传的图片地址
const fileList = ref<UploadUserFile[]>([])

// 图片预览
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  ruleForm.value.img = ''
  ruleFormRef.value?.validateField('img')
}

// 图片预览
const handlePictureCardPreview: UploadProps['onPreview'] = uploadFile => {
  prviewImageUrl.value = uploadFile.url!
  previewDialogVisible.value = true
}

/**
 * response：上传成功之后，服务器回来的响应
 * uploadFile：此次上传的那个文件
 * uploadFiles：上传成功之后，fileList中数组的表现（上传成功之后，数组新增一个）
 */
const handleSuccess = (response: any) => {
  ruleForm.value.img = response.fileUrl

  // ruleFormRef.value?.validateField('img')

  // 可以校验多个
  ruleFormRef.value?.validateField(['img'])
}
</script>

<style>
.el-image-viewer__canvas {
  z-index: 9999999 !important;
}
.el-image-viewer__canvas img {
  z-index: 9999999 !important;
}
</style>
